package com.smart.community.commons.websocket.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.smart.community.commons.websocket.SimpleWebSocketMessage;
import com.smart.community.commons.websocket.WebSocketMessage;
import com.smart.community.commons.websocket.WebSocketMessageType;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket工具类
 * 
 * @author Wu.Liang
 * @since 2025-01-30
 */
@Slf4j
public class WebSocketUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 创建系统消息
     * 
     * @param messageType 消息类型
     * @param content 消息内容
     * @return WebSocket消息
     */
    public static SimpleWebSocketMessage createSystemMessage(String messageType, Object content) {
        SimpleWebSocketMessage message = new SimpleWebSocketMessage(messageType, content);
        message.setSenderId(0L); // 系统消息
        message.setSenderName("SYSTEM");
        message.setTimestamp(LocalDateTime.now());
        message.setStatus(WebSocketMessage.MessageStatus.SENT);
        return message;
    }

    /**
     * 创建错误消息
     * 
     * @param errorMessage 错误信息
     * @return WebSocket消息
     */
    public static SimpleWebSocketMessage createErrorMessage(String errorMessage) {
        return createSystemMessage(WebSocketMessageType.ERROR.getCode(), errorMessage);
    }

    /**
     * 创建通知消息
     * 
     * @param title 通知标题
     * @param content 通知内容
     * @param type 通知类型
     * @return WebSocket消息
     */
    public static SimpleWebSocketMessage createNotificationMessage(String title, String content, String type) {
        Map<String, Object> notification = new HashMap<>();
        notification.put("title", title);
        notification.put("content", content);
        notification.put("type", type);
        notification.put("timestamp", LocalDateTime.now());
        
        return createSystemMessage(WebSocketMessageType.NOTIFICATION.getCode(), notification);
    }

    /**
     * 创建聊天消息
     * 
     * @param senderId 发送者ID
     * @param senderName 发送者名称
     * @param content 消息内容
     * @param targetRoom 目标房间
     * @return WebSocket消息
     */
    public static SimpleWebSocketMessage createChatMessage(Long senderId, String senderName, 
                                                          String content, String targetRoom) {
        SimpleWebSocketMessage message = new SimpleWebSocketMessage(WebSocketMessageType.CHAT.getCode(), content);
        message.setSenderId(senderId);
        message.setSenderName(senderName);
        message.setTargetRoom(targetRoom);
        message.setTimestamp(LocalDateTime.now());
        message.setStatus(WebSocketMessage.MessageStatus.SENT);
        return message;
    }

    /**
     * 将消息转换为JSON字符串
     * 
     * @param message WebSocket消息
     * @return JSON字符串
     */
    public static String toJson(WebSocketMessage message) {
        try {
            return objectMapper.writeValueAsString(message);
        } catch (JsonProcessingException e) {
            log.error("消息序列化失败，错误: {}", e.getMessage(), e);
            return "{}";
        }
    }

    /**
     * 从JSON字符串解析消息
     * 
     * @param json JSON字符串
     * @return WebSocket消息
     */
    public static SimpleWebSocketMessage fromJson(String json) {
        try {
            return objectMapper.readValue(json, SimpleWebSocketMessage.class);
        } catch (JsonProcessingException e) {
            log.error("消息反序列化失败，错误: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 检查消息类型是否为系统消息
     * 
     * @param messageType 消息类型
     * @return 是否为系统消息
     */
    public static boolean isSystemMessage(String messageType) {
        return WebSocketMessageType.isSystemMessage(messageType);
    }

    /**
     * 检查消息类型是否为聊天消息
     * 
     * @param messageType 消息类型
     * @return 是否为聊天消息
     */
    public static boolean isChatMessage(String messageType) {
        return WebSocketMessageType.isChatMessage(messageType);
    }

    /**
     * 生成消息ID
     * 
     * @return 消息ID
     */
    public static String generateMessageId() {
        return java.util.UUID.randomUUID().toString();
    }

    /**
     * 验证消息格式
     * 
     * @param message WebSocket消息
     * @return 是否有效
     */
    public static boolean isValidMessage(WebSocketMessage message) {
        return message != null && 
               message.getMessageId() != null && 
               message.getMessageType() != null && 
               message.getTimestamp() != null;
    }
}
